import axios from 'axios';
import { ElMessage } from 'element-plus';

import router from '../router/index.js';

const TOKEN_INVALID = 'token 认证失败，请重新登陆！';
const ENTWORK_ERROR = '网络请求异常，请稍后重试！';

//创建axios实例对象，添加全局配置
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 8000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

//请求拦截
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['access-token'] = token; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

service.interceptors.response.use(
  (res) => {
    if (!res.data.error) {
      return res.data;
    } else if (res.data.error === 'auth_fail') {
      //token 过期
      ElMessage({
        message: TOKEN_INVALID,
        type: 'error',
        grouping: true
      });
      const timer = setTimeout(() => {
        localStorage.clear();
        router.push({ path: '/login' });
        clearTimeout(timer);
      }, 1500);
      return Promise.reject(TOKEN_INVALID);
    } else {
      ElMessage.error(res.data.message || ENTWORK_ERROR);
      return Promise.reject(res.data.message || ENTWORK_ERROR);
    }
  },
  (err) => {
    ElMessage.error(err?.response?.data?.message || ENTWORK_ERROR);
    return err;
  }
);

export function request(options) {
  return new Promise((resolve, reject) => {
    service(options)
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}
